import axios, { AxiosRequestConfig } from "axios";
import { ElMessage } from "element-plus";

const request = axios.create({
  baseURL: "/api",
  timeout: 5000,
  headers: {
    uuid: Math.random().toString(36).substr(2),
  },
});

request.interceptors.response.use(
  (response): unknown => {
    const { error, msg, data } = response.data;
    if (error === false) {
      return data;
    } else {
      ElMessage.error("未请求到对应数据。");
      return Promise.reject(msg || "Error");
    }
  },
  (error) => {
    ElMessage.error(error);
    return Promise.reject(error);
  }
);

request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    return config;
  },
  (error) => {
    ElMessage.error(error);
    return Promise.reject(error);
  }
);

export function postPicture(b64: string): Promise<Array<string>> {
  return request.post("/pic", { base64: b64 });
}

export function postCancel() {
  return request.post("/cancel");
}

export function getResult(): Promise<Array<string>> {
  return request.get("/result");
}
